<?php
namespace Library;
/**
 * Description of BackController
 *
 * @author FFOZEU
 */
use Library\PHPMailer\PHPMailer;

abstract class BackController extends ApplicationComponent{
    
    protected $action = '';
    protected $module = '';
    protected $page = null;
    protected $view = '';
    protected $errors = '';
    protected $infos = '';
    protected $managers = null;


    public function __construct(Application $app, $module,$action){
        parent::__construct($app);
        $this->managers = new Managers('PDO', DbFactory::getPdoInstance());
        $this->page = new Page($app);
        $this->setModule($module);
        $this->setAction($action);
        $this->setView($action);
    }
    
    public function execute(){
        $method = 'execute'.ucfirst($this->action);
        if (!is_callable(array($this, $method))){
            throw new \RuntimeException('L\'action "'.$this->action.'" n\'est pas définie sur ce module');
        }
        $this->$method($this->app->httpRequest());
    }
    
    public function page(){
        return $this->page;
    }
    
    public function setModule($module){
        if (!is_string($module) || empty($module)){
            throw new \InvalidArgumentException('Le module doit être une chaine de caractères valide');
        }
        $this->module = $module;
    }
    public function setAction($action){
        if (!is_string($action) || empty($action)){
            throw new \InvalidArgumentException('L\'action doit être une chaine de caractères valide');
        }
        $this->action = $action;
    }
    public function setView($view){
        if (!is_string($view) || empty($view)){
            throw new \InvalidArgumentException('La vue doit être une chaine de caractères valide');
        }
        $this->view = $view;
        $this->page->setContentFile(dirname(__FILE__).'/../Applications/Modules/'.$this->module.'/'.$this->app->name().'/Views/'.ucfirst($this->view).'.tpl.php');
    }
    
    public function sendMail(array $param){
        $mail = new PHPMailer();
        //$mail->IsSendmail();
        $mail->IsSMTP();
        try {
            //$mail->Body = $message;
            $mail->AddReplyTo($param['destinataire']);
            $mail->SetFrom($param['from']);
            $mail->AddReplyTo($param['destinataire']);
            $mail->AddAddress($param['adress'], "Visitor");
            $mail->Subject = $param['subjet'];
            $mail->MsgHTML($param['message']);
            if($mail->Send()){
                $this->infos = "Votre Message a été envoyé avec succès";
            }else{
                $this->errors = "echec lors de l'envoi";
            }

        } catch (phpmailerException $e) {
            $this->errors =  $e->errorMessage(); //Pretty error messages from PHPMailer
        } catch (Exception $e) {
            $this->errors = $e->getMessage(); //Boring error messages from anything else!
        }
    }
}

?>
